package fun.shuofeng.juc.deadlock;

import java.util.concurrent.TimeUnit;

public class TheDiningPhilosophersProblem {
    public static void main(String[] args) {
        Chopstick a = new Chopstick("A");
        Chopstick b = new Chopstick("B");
        Chopstick c = new Chopstick("C");
        Chopstick d = new Chopstick("D");
        Chopstick e = new Chopstick("E");
        new Philosopher("Tom", a, b).start();
        new Philosopher("Jack", b, c).start();
        new Philosopher("Bob", c, d).start();
        new Philosopher("Lili", d, e).start();
        new Philosopher("Ewan", e, a).start();
    }
}

class Philosopher extends Thread {

    private final Chopstick left;
    private final Chopstick right;

    public Philosopher(String name, Chopstick left, Chopstick right) {
        super(name);
        this.left = left;
        this.right = right;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (left) {
                synchronized (right) {
                    eat();
                    think();
                }
            }
        }
    }

    private void think() {
        try {
            System.out.println(this.getName() + " think...");
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    private void eat() {
        System.out.println(this.getName() + " eat...");
    }
}

class Chopstick {
    String name;

    public Chopstick(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Chopstick{" +
                "name='" + name + '\'' +
                '}';
    }
}